package com.xhj.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhj.entity.Permission;
import com.xhj.entity.RolePermission;
import com.xhj.entity.User;
import com.xhj.entity.UserRole;
import com.xhj.mapper.PermissionMapper;
import com.xhj.service.PermissionService;
import com.xhj.service.RolePermissionService;
import com.xhj.service.UserRoleService;
import com.xhj.service.UserService;
import com.xhj.util.AclUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 * 权限(Permission)表服务实现类
 *
 * @author makejava
 * @since 2021-03-15 12:26:24
 */
@Service
@Slf4j
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper,Permission> implements PermissionService {

    @Autowired
    private RolePermissionService rolePermissionService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private UserService userService;

    public static final String ADMIN_ID = "1";

    @Override
    public List<Permission> queryAllMenu() {
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        List<Permission> permissionList = baseMapper.selectList(queryWrapper);
        // 构建树形数据
        return AclUtils.build(permissionList);
    }

    @Override
    public void removeMenu(String id) {
        Permission permission = baseMapper.selectById(id);
        ArrayList<String> idList = new ArrayList<>();
        // 递归找出所有的子id
        AclUtils.findIds(permission,idList);
        idList.add(id);
        // 批量删除
        baseMapper.deleteBatchIds(idList);
    }

    @Override
    public void saveRolePermissionRelationShip(String roleId, String[] permissionIds) {
        // 先删除原角色权限关系
        QueryWrapper<RolePermission> queryWrapper = new QueryWrapper<RolePermission>().eq("role_id", roleId);
        rolePermissionService.remove(queryWrapper);
        // 清空菜单
        if (permissionIds == null) return;
        ArrayList<RolePermission> rolePermissionList = new ArrayList<>();
        // 遍历permissionId
        for (String permissionId : permissionIds) {
            if (StringUtils.isEmpty(permissionId)) continue;
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(permissionId);
            // rolePermissionList
            rolePermissionList.add(rolePermission);
        }
        log.info(rolePermissionList.toString());
        rolePermissionService.saveBatch(rolePermissionList);
    }

    @Override
    public List<String> selectPermissionValueByUserId(String uid) {
        ArrayList<String> authorities = new ArrayList<>();
        if (isAdmin(uid)){
            // 假如是管理员获得所有权限
            authorities = baseMapper.selectAllPermissionValue();
        }else {
            authorities = baseMapper.selectPermissionValueByUserId(uid);
        }
        return authorities;
    }

    @Override
    public List<Permission> queryMenuByRoleId(String roleId) {
        // 查询所有菜单
        List<Permission> allPermissionList = baseMapper.selectList(null);
        // 查询该角色所有的菜单权限
        QueryWrapper<RolePermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id",roleId);
        List<RolePermission> rolePermissionList = rolePermissionService.list(queryWrapper);
        // 遍历rolePermissionList  allPermissionList
        for (Permission permission : allPermissionList) {
            for (RolePermission rolePermission : rolePermissionList) {
                if (rolePermission.getPermissionId().equals(permission.getId())) permission.setSelect(true);
            }
        }
        // 构建树形菜单
        List<Permission> menuList = AclUtils.build(allPermissionList);
        return menuList;
    }

    @Override
    public List<JSONObject> getMenuByUserName(String username) {
        // 根据用户名查询用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        User user = userService.getOne(queryWrapper);

        List<Permission> selectPermissionList = null;
        if(this.isAdmin(user.getId())) {
            //如果是超级管理员，获取所有菜单
            selectPermissionList = baseMapper.selectList(null);
        } else {
            selectPermissionList = baseMapper.selectPermissionByUserId(user.getId());
        }
        List<Permission> permissionList = AclUtils.build(selectPermissionList);
        // 构建Json格式的菜单
        List<JSONObject> menuList = AclUtils.buildJsonList(permissionList);
        log.info(menuList.toString());
        return menuList;
    }

    /**
     * 判断是否是管理员
     * @param uid
     * @return
     */
    private boolean isAdmin(String uid){
        return ADMIN_ID.equals(uid);
    }

}